﻿using System;
using System.Globalization;

namespace Ewk.Runtime.Serialization.PositionBased
{
    class PositionBasedDateTimeSerializer : DatafieldSerializer<PositionBasedDatafieldAttribute>
    {
        public override string Serialize(object datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            var value = (DateTime) datafield;
            if (value == default(DateTime))
            {
                return new string(datafieldAttribute.DefaultCharacter, datafieldAttribute.Length);
            }

            return value.ToString(datafieldAttribute.Format, CultureInfo.CurrentCulture);
        }

        public override object Deserialize(string datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            if (string.IsNullOrEmpty(datafield))
            {
                return default(DateTime);
            }

            DateTime result;
            if (DateTime.TryParse(datafield, out result))
            {
                return result;
            }

            var exceptionMessage = string.Format(CultureInfo.CurrentCulture, ExceptionMessages.CannotDeserializeValue, datafield, DatafieldType);
            OnDatafieldSerializationFailed(exceptionMessage);

            return default(DateTime);
        }

        public override Type DatafieldType
        {
            get { return typeof(DateTime); }
        }
    }
}
